package main

import (
	"context"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v9"
	goredislib "github.com/redis/go-redis/v9"
	"shop/cart-srv/proto"
	"sync"
)

import "google.golang.org/grpc"

var conn *grpc.ClientConn
var inventorClient proto.InvertoryClient

func Init() {
	var err error
	conn, err = grpc.Dial("127.0.0.1:6002", grpc.WithInsecure())
	if err != nil {
		panic("dial to fail: " + err.Error())
	}

	inventorClient = proto.NewInvertoryClient(conn)

}

func TestGetInventor() {
	inventorClient.SetInv(context.Background(), &proto.GoodsInvInfo{
		GoodsId: 10,
		Num:     10,
	})
}

func TestSell(wg *sync.WaitGroup) {
	inventorClient.Sell(context.Background(), &proto.SellInfo{})
	wg.Done()
}
func main() {

	client := goredislib.NewClient(&goredislib.Options{
		Addr: "localhost:6379",
	})
	pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)

	// Create an instance of redisync to be used to obtain a mutual exclusion
	// lock.
	rs := redsync.New(pool)

	// Obtain a new mutex by using the same name for all instances wanting the
	// same lock.
	mutexname := "my-global-mutex"
	mutex := rs.NewMutex(mutexname)

	// Obtain a lock for our given mutex. After this is successful, no one else
	// can obtain the same lock (the same mutex name) until we unlock it.
	if err := mutex.Lock(); err != nil {
		panic(err)
	}

	// Do your work that requires the lock.

	// Release the lock so other processes or threads can obtain a lock.
	if ok, err := mutex.Unlock(); !ok || err != nil {
		panic("unlock failed")
	}

	Init()
	wg := &sync.WaitGroup{}
	wg.Add(20)
	for i := 0; i < 20; i++ {
		go func() {
			inventorClient.Sell(context.Background(), &proto.SellInfo{})
			wg.Done()
		}()
	}
	wg.Wait()

	conn.Close()

}
